package com.jfinal.plugin.zbus.proto;

import com.jfinal.log.Logger;
import org.zbus.broker.Broker;
import org.zbus.broker.BrokerConfig;
import org.zbus.broker.SingleBroker;

import java.io.IOException;

/**
 * zbus的代理对象,主要包含的操作:
 * init,create
 * Created by dairymix on 17/5/5.
 */
public class ZbusBroker {

    private static final Logger log = Logger.getLogger(ZbusBroker.class);


    public Broker me = null; //broker对象

    public String address = null; //broker地址
    public BrokerConfig config = null; //broker配置

    public ZbusBroker init(String address, BrokerConfig config){
        //this.btype = zbus;
        this.address = address;
        this.config = config;
        return this;
    }

    public ZbusBroker init(BrokerConfig config){
        return init("127.0.0.1:15555",config);
    }

    public ZbusBroker init(String address){
        return init(address,null);
    }

    /**
     * 默认采用zbus配置构造函数，使用127.0.0.1:15555地址
     */
    public ZbusBroker init(){
        return init((BrokerConfig)null);
    }

    /**
     * @Title: create
     * @Description: 创建可用的broker
     * @throws Exception
     * @since V1.0.0
     */
    public ZbusBroker create(){
        if(me == null){ //没有构造broker对象
            synchronized (this) {
                if(me == null){ //当broker对象为空

                    //设置broker的配置参数
                    if(this.address == null){
                        this.address = "localhost:15555";
                    }
                    this.config = new BrokerConfig();
                    this.config.setBrokerAddress(address);

                    try { //根据配置参数创建broker对象
                        me = new SingleBroker(this.config);
                        log.info("创建broker成功(address=" + this.address + ")");
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage(),e);
                    }
                }
            }
        }
        return this;
    }

    public ZbusBroker doing(String address, BrokerConfig config){
        return init(address,config).create();
    }

    public ZbusBroker doing(String address){
        return init(address).create();
    }

    public ZbusBroker doing(BrokerConfig config){
        return init(config).create();
    }

    public ZbusBroker doing(){
        return init().create();
    }

    // 关闭broker
    public ZbusBroker close(){
        try {
            if (me != null) {
                me.close();
                me = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this;
    }
}
